package com.jmoney.luckeylink.handler;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.testng.Assert;
import org.testng.Reporter;

import com.jmoney.luckeylink.controller.LekeU_Captcha_Controller;
import com.jmoney.luckeylink.util.ExcelUtil;
import com.jmoney.luckeylink.util.HttpGetRequestUtil;
import com.jmoney.luckeylink.util.MobileApiToolsUtil;
import com.jmoney.luckeylink.util.DecodeUnicodeUtil;

public class LekeU_Captcha_Handler {
    private static Logger logger = Logger.getLogger(LekeU_Captcha_Handler.class);
    static int TITLE_LINE_INDEX=5;
    
    static String Param = null;
    
	/**
	 * <br>获取Excel数据</br>
	 * @author  刘智King
	 * @date     2018年4月20日 下午6:01:04
	 */
    public static void GetExcelInstance() {
        logger.info(LekeU_Captcha_Handler.class);
        System.out.println(LekeU_Captcha_Handler.class);
		ExcelUtil.getInstance().setFilePath("src/test/java/TestCasexls/JMoney.Luckeylink.Api.xlsm");
		ExcelUtil.getInstance().setSheetName("LekeU_Captcha");
    }
    
	/**
	 * <br>初始化Excel数据</br>
	 * @author  刘智King
	 * @date     2018年4月20日 下午6:01:04
	 */
    public static void InitializeExcelData() { 
        try {
            logger.info("初始化: " + ExcelUtil.getInstance().getFilePath() + ", " + ExcelUtil.getInstance().getSheetName());
            System.out.println("初始化: " + ExcelUtil.getInstance().getFilePath() + ", " + ExcelUtil.getInstance().getSheetName());
            MobileApiToolsUtil.initializeData(5, "Run", "", 4);
//            MobileApiToolsUtil.initializeData(5, "message_Exp", "", 4);
            MobileApiToolsUtil.initializeData(5, "message_Act", "", 4);
//            MobileApiToolsUtil.initializeData(5, "ActualResult", "", 4);
            MobileApiToolsUtil.initializeData(5, "StatusCode", "", 4);
            MobileApiToolsUtil.initializeData(5, "TestResult", "", 4);
            MobileApiToolsUtil.initializeData(5, "RunningTime", "", 4);
            MobileApiToolsUtil.initializeData(5, "Json", "", 4);
            MobileApiToolsUtil.initializeData(5, "FailHint", "", 4);
            logger.info(ExcelUtil.getInstance().getFilePath() + ", " + ExcelUtil.getInstance().getSheetName() + "初始化完成");
            System.out.println(ExcelUtil.getInstance().getFilePath() + ", " + ExcelUtil.getInstance().getSheetName() + "初始化完成");
            System.out.println("==================================================================");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

	/**
	 * <br>根据数据库版本和用例ID，从数据库获取信息并写入到Excel预期值</br>
	 * @author  刘智King
	 * @date     2018年4月20日 下午6:01:04
	 * @param  DataVersion
	 * @param  ID
	 */
    public static void WriteExcelExpected(String DataVersion,int ID){ 
    	
    	List<Map<String, String>> data = null;
        data = ExcelUtil.getInstance().readExcelAllData(TITLE_LINE_INDEX);
        
        try {
        	if (data != null) {
//                for (int i = 0; i < data.size(); i++) {
        		  int i = ID;
        	      Map<String, String> map = data.get(i);
                  String Sql =map.get("userId");

                  logger.info("根据数据库查询结果, 开始写入预期值【Waiting...】");
                  System.out.println("根据数据库查询结果, 开始写入预期值【Waiting...】");
                  
//                  String $id_Exp= DataBase_Util.GetSqlResult(DataVersion, Sql,"$id_Exp");
        	      MobileApiToolsUtil.writeResult(TITLE_LINE_INDEX-1, TITLE_LINE_INDEX + i, "$id_Exp", "2");
        	      
        	      String phone_Exp= LekeU_Captcha_Controller.GetSqlResult(DataVersion, Sql,"phone");
        	      MobileApiToolsUtil.writeResult(TITLE_LINE_INDEX-1, TITLE_LINE_INDEX + i, "phone_Exp", phone_Exp);

        	      String roleId_Exp= LekeU_Captcha_Controller.GetSqlResult(DataVersion, Sql,"roleId");
        	      MobileApiToolsUtil.writeResult(TITLE_LINE_INDEX-1, TITLE_LINE_INDEX + i, "roleId_Exp", roleId_Exp);
        	
        	      String roleName_Exp= LekeU_Captcha_Controller.GetSqlResult(DataVersion, Sql,"roleName");
        	      MobileApiToolsUtil.writeResult(TITLE_LINE_INDEX-1, TITLE_LINE_INDEX + i, "roleName_Exp", roleName_Exp);
        	      
        	      String salesId_Exp= LekeU_Captcha_Controller.GetSqlResult(DataVersion, Sql,"salesId");
        	      MobileApiToolsUtil.writeResult(TITLE_LINE_INDEX-1, TITLE_LINE_INDEX + i, "salesId_Exp", salesId_Exp);
        	      
        	      String userName_Exp= LekeU_Captcha_Controller.GetSqlResult(DataVersion, Sql,"userName");
        	      MobileApiToolsUtil.writeResult(TITLE_LINE_INDEX-1, TITLE_LINE_INDEX + i, "userName_Exp", userName_Exp);
        	      
//        	      String identification_Exp= DataBase_Util.GetSqlResult(DataVersion, Sql,"identification");
        	      MobileApiToolsUtil.writeResult(TITLE_LINE_INDEX-1, TITLE_LINE_INDEX + i, "identification_Exp", "string");
        	      
        	      String photoName_Exp= LekeU_Captcha_Controller.GetSqlResult(DataVersion, Sql,"photoName");
        	      MobileApiToolsUtil.writeResult(TITLE_LINE_INDEX-1, TITLE_LINE_INDEX + i, "photoName_Exp", "http://10.10.11.136/"+photoName_Exp);
        	      
                 logger.info("对应用例预期值,写入成功【OK】");
                 System.out.println("对应预期值,写入成功【OK】");
                 System.out.println("==================================================================");
               }
//            } 
        }catch (IOException e) {
            e.printStackTrace();
        }
    }
    
	/**
	 * <br>根据用例ID，执行Login相关接口请求，获取Json信息，并写入结果到Excel</br>
	 * @author  刘智King
	 * @date     2018年4月20日 下午6:01:04
	 * @param  ID
	 */
    public static void Captcha(int ID) throws Exception {

        List<Map<String, String>> data = null;
        boolean ArgName = false;

        String ApiUrl = ExcelUtil.getInstance().readExcelCell(1, 2);
        String Act = ExcelUtil.getInstance().readExcelCell(2, 2);
        String Method = ExcelUtil.getInstance().readExcelCell(3, 2);
        ArgName = MobileApiToolsUtil.isArgEquals(4, 2, TITLE_LINE_INDEX);

        if (ApiUrl.equals("") || Act.equals("") || Method.equals("") || !ArgName) {
            logger.error("请检查 Excel 中 ApiUrl、Act、Method、ArgName 是否设置正确...");
            System.out.println("请检查 Excel 中 ApiUrl、Act、Method、ArgName 是否设置正确...");
            System.exit(-1);
        }

        data = ExcelUtil.getInstance().readExcelAllData(TITLE_LINE_INDEX);

        if (data != null) {
        	
            int i = ID;
            //根据Excel列名称,获取单元格内容
            Map<String, String> map = data.get(i-1);
            String CaseID = map.get("CaseID");
            String CaseName = map.get("CaseName");
            String mobile = map.get("mobile");
            String sign = map.get("sign");
            String message_Exp = map.get("message_Exp");
            
            //写入Run列, 执行纪录
            MobileApiToolsUtil.writeResult(TITLE_LINE_INDEX, TITLE_LINE_INDEX + i, "Run", "Y");

            //指定请求的Api地址
            Param = "mobile="+mobile+"&sign="+sign+"";
            String CaptchaApiUrl=ApiUrl+"?"+Param;
            
            //请求接口，获取StatusCode结果并写入
            int Code = HttpGetRequestUtil.GetJsonDataIntValue(CaptchaApiUrl,"status_code");
            MobileApiToolsUtil.writeResult(TITLE_LINE_INDEX, TITLE_LINE_INDEX + i, "StatusCode", String.valueOf(Code));
            
            //判断Code结果是否等于200，成立则TestResult写入OK并设置单元格颜色为绿色，反则写入NG并设置单元格颜色为红色，并写入失败消息提示
            if (Code == 200){
            	ExcelUtil.getInstance().setCellBackgroundColor(TITLE_LINE_INDEX, "StatusCode",TITLE_LINE_INDEX + i, 1);
            	MobileApiToolsUtil.writeResult(TITLE_LINE_INDEX, TITLE_LINE_INDEX + i, "TestResult", "OK");
                ExcelUtil.getInstance().setCellBackgroundColor(TITLE_LINE_INDEX, "TestResult",TITLE_LINE_INDEX + i, 1);
            }else{
            	ExcelUtil.getInstance().setCellBackgroundColor(TITLE_LINE_INDEX, "StatusCode",TITLE_LINE_INDEX + i, 0);
            	MobileApiToolsUtil.writeResult(TITLE_LINE_INDEX, TITLE_LINE_INDEX + i, "TestResult", "NG");
            	ExcelUtil.getInstance().setCellBackgroundColor(TITLE_LINE_INDEX, "TestResult",TITLE_LINE_INDEX + i, 0);
            	//请求接口，获取message消息结果并写入
                String message = HttpGetRequestUtil.GetJsonDataStringValue(CaptchaApiUrl,"message");
                MobileApiToolsUtil.writeResult(TITLE_LINE_INDEX, TITLE_LINE_INDEX + i, "FailHint", "【message】"+message+"");
            }

            //写入执行时间
            MobileApiToolsUtil.writeResult(TITLE_LINE_INDEX, TITLE_LINE_INDEX + i, "RunningTime", MobileApiToolsUtil.getDate());

            //请求接口，获取JSON结果并编码转换后写入
            String JsonResult = HttpGetRequestUtil.GetJsonResult(CaptchaApiUrl);
            String NewJsonResult=DecodeUnicodeUtil.decodeUnicode(JsonResult);
            MobileApiToolsUtil.writeResult(TITLE_LINE_INDEX, TITLE_LINE_INDEX + i, "Json", NewJsonResult);
            
	        //请求接口，获取message_Act结果并写入
            String message_Act = HttpGetRequestUtil.GetJsonDataStringValue(CaptchaApiUrl,"message");
            MobileApiToolsUtil.writeResult(TITLE_LINE_INDEX, TITLE_LINE_INDEX + i, "message_Act", message_Act);
            
            Reporter.log("用例ID: "+ CaseID);        
	        Reporter.log("用例名称: "+ CaseName);
	        Reporter.log("请求地址: "+ ApiUrl);
	        Reporter.log("请求方式: "+ Method);
	        Reporter.log("请求参数: "+ Param);
	        Reporter.log("返回结果: "+ NewJsonResult);
	        
            //检查message预期结果和实际结果是否正确
	        checkEquals(message_Exp,message_Act,"message_Exp","message_Act",ID);	   
        }
//        }
    }
    
	/**
	 * <br>根据用例ID，获取用例名称信息，打印到控制台并写入Excel</br>
	 * @author  刘智King
	 * @date     2018年4月20日 下午6:01:04
	 * @param  ID
	 */
    public static void GetCaseInfo(int ID) throws Exception {
    	
    	List<Map<String, String>> data = null;
    	data = ExcelUtil.getInstance().readExcelAllData(TITLE_LINE_INDEX);

    	if (data != null) {
//            for (int i = 0; i < data.size(); i++) {
                int i = ID;
                
            	//根据Excel列名称,获取单元格内容
                Map<String, String> map = data.get(i-1);
                String CaseID = map.get("CaseID");
                String CaseName = map.get("CaseName");
                String message_Exp = map.get("message_Exp");
                String message_Act = map.get("message_Act");
                String StatusCode = map.get("StatusCode");
                String TestResult = map.get("TestResult");
                String FailHint = map.get("FailHint");

                //打印日志
                logger.info("CaseID: " + CaseID + ", CaseName: " + CaseName +  
                ", message_Exp: " + message_Exp +", message_Act: " + message_Act+ 
                ", StatusCode: " + StatusCode +", TestResult: " + TestResult+ ", FailHint: " + FailHint);
                logger.info("==================================================================");

                
                System.out.println("CaseID: " + CaseID + ", CaseName: " + CaseName + 
                ", message_Exp: " + message_Exp +", message_Act: " + message_Act+ 
                ", StatusCode: " + StatusCode +", TestResult: " + TestResult + ", FailHint: " + FailHint);
                System.out.println("==================================================================");
            }
//        }
    }
    
	/**
	 * <br>根据用例ID，检查预期与实际是否相等，不等则提示错误信息，并写入结果</br>
	 * @author  刘智King
	 * @date     2018年4月20日 下午6:01:04
	 * @param  ID
	 */
	public static void checkEquals(String Expected,String Actual,String ExpectedList,String ActualList,int ID) throws Exception{
		int i = ID;
		try {
			Assert.assertEquals(Expected,Actual);
			MobileApiToolsUtil.writeResult(TITLE_LINE_INDEX, TITLE_LINE_INDEX + i, "TestResult", "OK");
            ExcelUtil.getInstance().setCellBackgroundColor(TITLE_LINE_INDEX, "TestResult",TITLE_LINE_INDEX + i, 1);
			Reporter.log("用例结果: 〖"+ExpectedList.replace("_Exp", "")+"〗=>Expected: " + "【"+Expected+"】" + ", Actual: "+ "【"+Actual+"】");
	        System.out.println("用例结果: 【"+ExpectedList.replace("_Exp", "")+"】=>Expected: " + "【"+Expected+"】" + ", Actual: "+ "【"+Actual+"】");
        }catch (Error e)  {
 	    	MobileApiToolsUtil.writeResult(TITLE_LINE_INDEX, TITLE_LINE_INDEX + i, "TestResult", "NG");
        	ExcelUtil.getInstance().setCellBackgroundColor(TITLE_LINE_INDEX, "TestResult",TITLE_LINE_INDEX + i, 0);
 	    	ExcelUtil.getInstance().setCellBackgroundColor(TITLE_LINE_INDEX, ActualList,TITLE_LINE_INDEX + i, 3);
 	    	MobileApiToolsUtil.writeResult(TITLE_LINE_INDEX, TITLE_LINE_INDEX + i, "FailHint", "【"+ExpectedList+"】和【"+ActualList+"】不一致");
 	    	Assert.fail(""+ExpectedList.replace("_Exp", "")+" =>Expected 【"+ Expected +"】"+" "+"but found 【"+ Actual +"】");
 	    }
	}
}